﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Model.DocumentDB
{
    /// <summary>Represents a folder containing a collection of items.</summary>
    public abstract class FolderViewModel
    {
        /// <summary>Constructor.</summary>
        /// <param name="displayName">Display name of the folder.</param>
        public FolderViewModel(string displayName)
        {
            if (string.IsNullOrWhiteSpace(displayName))
            {
                throw new ArgumentNullException("displayName");
            }

            FolderDisplayName = displayName;
        }

        /// <summary>Name of the folder.</summary>
        public string FolderDisplayName { get; private set; }

        /// <summary>Ensures the folder content is loaded.</summary>
        /// <returns>Asynchronous completion.</returns>
        public abstract Task EnsureLoadedAsync();
    }

    /// <summary>Represents a folder containing a collection of strong type items.</summary>
    public class FolderViewModel<T> : FolderViewModel, IRefreshable
    {
        /// <summary>Constructor.</summary>
        /// <param name="displayName">Display name of the folder.</param>
        /// <param name="folderContent">Collection content.</param>
        public FolderViewModel(string displayName, LoadableCollection<T> folderContent)
            : base(displayName)
        {
            if (folderContent == null)
            {
                throw new ArgumentNullException("folderContent");
            }

            FolderContent = folderContent;
        }

        /// <summary>Content of the folder.</summary>
        public LoadableCollection<T> FolderContent { get; private set; }

        /// <summary>Ensure <see cref="FolderContent"/> is loaded.</summary>
        /// <returns>Asynchronous completion.</returns>
        public override Task EnsureLoadedAsync()
        {
            return FolderContent.EnsureLoadedAsync();
        }

        Task IRefreshable.RefreshAsync()
        {
            if (FolderContent.IsLoading)
            {   //  Already loading
                return Task.FromResult(42);
            }
            else if (FolderContent.IsLoaded || FolderContent.HasError)
            {
                return FolderContent.RefreshAsync();
            }
            else
            {
                return FolderContent.EnsureLoadedAsync();
            }
        }
    }
}